/**
 * @description 字符组件
 * @author Rid King
 * @since 2018-02-04
*/

export default {
  // 删减字符
  pad (source, len, char, from) {
    char = char || '0'
    source = source.toString()
    var pre = source.length < len ? (new Array(len - source.length + 1)).join(char) : ''
    return from == 'left' ? (pre + source) : (source + pre)
  },

  //删除左边字符
  padLeft (source, len, char) {
    return this.pad(source, len, char, 'left')
  },

  //删除右边字符
  padRight (source, len, char) {
    return this.pad(source, len, char, 'right')
  },

  /**
   * @function 生成uuid
   * @param {Int} len 字符长度,最小长度为1
   * @return {String}
   * */
  uuid (len) {
    len = parseInt(len)
    if (isNaN(len)) {
      len = 6
    }
    if (len < 1) {
      len = 1
    }
    var s = []
    var hexDigits = '0123456789abcdef'
    for (var i = 0; i < len; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    var uuid = s.join('')
    return uuid
  },

  /**
   * @function 生成utid
   * @param {Int} len 字符长度,最小10
   * @return {String}
   * */
  utid (len) {
    len = parseInt(len) || 12
    len = len < 12 ? 12 : len
    // 当前时间戳
    let timeId = ((new Date).getTime()).toString(36)
    // 剩余长度随机
    while(timeId.length < len) {
      timeId += Math.floor(36 * Math.random()).toString(36)
    }

    return timeId
  },

  /**
   * @function 生成随机字符串
   * @param {Int} len 字符长度,最小长度为1
   * @param {Boolean} isOnlyLetter 是否纯字母
   * @param {Boolean} isOnlyNumber 是否纯数字
   * @return {String}
   * */
  urid (len, isOnlyLetter, isOnlyNumber) {
    len = parseInt(len)
    if (isNaN(len)) {
      len = 6
    }
    if (len < 1) {
      len = 1
    }
    var s = []
    var str = '0123456789abcdefghijklmnopqrstuvwxyz'
    // 纯字母
    if (isOnlyLetter === true) {
      str = str.slice(10)
    } else if (isOnlyNumber === true) {
      str = str.slice(0, 10)
    }
    for (var i = 0; i < len; i++) {
      let start = Math.floor(Math.random() * str.length)
      s[i] = str.substr(start, 1);
    }

    return s.join('')
  }
}